package com.supcalls.lock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class SharedData {
    private int data = 0;
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    // 读操作
    public int read() {
        lock.readLock().lock();  // 获取读锁
        try {
            return data;
        } finally {
            lock.readLock().unlock(); // 释放读锁
        }
    }

    // 写操作
    public void write(int newData) {
        lock.writeLock().lock();  // 获取写锁
        try {
            data = newData;
        } finally {
            lock.writeLock().unlock(); // 释放写锁
        }
    }
}

public class ReadWriteLockExample {
    public static void main(String[] args) {
        SharedData sharedData = new SharedData();

        // 读线程
        Thread reader1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Reader 1 read: " + sharedData.read());
            }
        });

        Thread reader2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Reader 2 read: " + sharedData.read());
            }
        });

        // 写线程
        Thread writer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                sharedData.write(i);
                System.out.println("Writer wrote: " + i);
            }
        });

        reader1.start();
        reader2.start();
        writer.start();
    }
}
